# -*- coding: utf-8 -*-

from odoo import api, fields, models, tools
from odoo.tools.translate import _


class SaleOrderReport(models.Model):
    _name = "tour.sale.order.report"
    _description = u"订单流量表"
    _auto = False

    paid_amount = fields.Float(string=u"支付总额", readonly=True)
    refund_amount = fields.Float(string=u"退款总额", readonly=True)
    money_date = fields.Date(string=u"统计日期", readonly=True)

    @api.model_cr
    def init(self):
        tools.drop_view_if_exists(self._cr, self._table)
        self._cr.execute("""
                create or replace view tour_sale_order_report as (
                    select MIN(id) as id, money_date, sum(paid_amount) as paid_amount, sum(refund_amount) as refund_amount from 
                    (SELECT
                            MIN(id) as id, to_char(write_date, 'YYYY-MM-DD') as money_date, SUM (order_amount) AS paid_amount, 0 AS refund_amount
                    FROM
                            sale_order
                    WHERE
                        STATE = 'paid'
                    group by money_date
                    UNION ALL
                    SELECT
                            MIN(id) as id, to_char(write_date, 'YYYY-MM-DD') as money_date, 0 AS paid_amount, SUM (refund_amount) AS refund_amount
                    FROM
                            sale_order
                    WHERE
                        STATE = 'done'
                    group by money_date
                    ) as sale_order GROUP BY money_date order by money_date)
                            """)


class SaleOrderReportWizard(models.TransientModel):
    _name = 'tour.sale.order.report.wizard'

    start_date = fields.Date(string=u'开始日期')
    end_date = fields.Date(string=u'结束日期')

    @api.multi
    def search_sale_order_report(self):
        self.ensure_one()
        domain = []
        for wizard in self:
            if wizard.start_date:
                domain += [('money_date', '>=', wizard.start_date)]
            if wizard.end_date:
                domain += [('money_date', '<=', wizard.end_date)]

        action = {
            'domain': domain,
            'name': _('Sale Order Report'),
            'type': 'ir.actions.act_window',
            'view_mode': 'tree',
            'res_model': 'tour.sale.order.report'
        }
        return action
